#include "zoomablepreview.h"
#include <QWheelEvent>
#include <QMouseEvent>
#include <QScrollBar>
#include <QGraphicsPixmapItem>

ZoomablePreview::ZoomablePreview(QWidget* parent) : QGraphicsView(parent)
{
    m_scene = new QGraphicsScene(this);
    setScene(m_scene);
    setRenderHint(QPainter::Antialiasing);
    setRenderHint(QPainter::SmoothPixmapTransform);
    setDragMode(QGraphicsView::ScrollHandDrag);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setMinimumSize(400, 300);
}

void ZoomablePreview::setImage(const QImage& image)
{
    m_scene->clear();
    
    // 设置场景大小为图片大小
    m_scene->setSceneRect(0, 0, image.width(), image.height());
    
    // 添加图片到场景
    QGraphicsPixmapItem* item = m_scene->addPixmap(QPixmap::fromImage(image));
    item->setPos(0, 0);
    
    // 不进行任何缩放
    setTransform(QTransform());
}

void ZoomablePreview::updateImageKeepView(const QImage& image)
{
    if (m_scene->items().isEmpty()) {
        setImage(image);
        return;
    }
    
    // 保存当前滚动条位置
    int hValue = horizontalScrollBar()->value();
    int vValue = verticalScrollBar()->value();
    
    // 更新图片但保持场景大小不变
    m_scene->clear();
    QGraphicsPixmapItem* item = m_scene->addPixmap(QPixmap::fromImage(image));
    item->setPos(0, 0);
    
    // 恢复滚动条位置
    horizontalScrollBar()->setValue(hValue);
    verticalScrollBar()->setValue(vValue);
}

void ZoomablePreview::wheelEvent(QWheelEvent* event)
{
    double scaleFactor = 1.15;
    if (event->angleDelta().y() < 0) {
        scaleFactor = 1.0 / scaleFactor;
    }
    scale(scaleFactor, scaleFactor);
}

void ZoomablePreview::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        m_lastPos = event->pos();
        m_isDragging = true;
        setCursor(Qt::ClosedHandCursor);
    }
    QGraphicsView::mousePressEvent(event);
}

void ZoomablePreview::mouseMoveEvent(QMouseEvent* event)
{
    if (m_isDragging) {
        QPointF delta = event->pos() - m_lastPos;
        horizontalScrollBar()->setValue(horizontalScrollBar()->value() - delta.x());
        verticalScrollBar()->setValue(verticalScrollBar()->value() - delta.y());
        m_lastPos = event->pos();
    }
    QGraphicsView::mouseMoveEvent(event);
}

void ZoomablePreview::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) {
        m_isDragging = false;
        setCursor(Qt::ArrowCursor);
    }
    QGraphicsView::mouseReleaseEvent(event);
}